package com.lnyt.serviceImpl;

import com.alibaba.fastjson.JSON;

import com.lnyt.service.ChatRobotService;
import com.lnyt.pojo.robot.InputRobot;
import com.lnyt.pojo.robot.OutputRobot;
import com.lnyt.util.CheckUtil;
import com.lnyt.util.LogUtil;
import com.lnyt.util.factroy.OutputRobotFactroy;
import okhttp3.*;

import java.io.IOException;


// 实现聊天机器人
public class ChatRobotServiceImpl implements ChatRobotService {
    // Json body
    private static MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
    // 机器人Url
    private String apiUrl = "";
    // 校验Key
    private String apiKey = "";

    public String getApiUrl() {
        return apiUrl;
    }
    public void setApiUrl(String apiUrl) {
        this.apiUrl = apiUrl;
    }

    public String getApiKey() {
        return apiKey;
    }
    public void setApiKey(String apiKey) {
        this.apiKey = apiKey;
    }

    // 得到图灵机器人回复
    public String getRobotMessage(String text, String loc, String openID) {
        LogUtil.log4j2().info("Tuling Robot call");

        String resData = null;
        String askerID = CheckUtil.calcMd5(openID);

        OutputRobot outputRobot = OutputRobotFactroy.creator(apiKey, text, loc, askerID);

        //创建一个OkHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(jsonType, JSON.toJSONString(outputRobot));
        Request request = new Request.Builder().url(apiUrl).post(requestBody).build();

        try {
            Response response = okHttpClient.newCall(request).execute();

            if (response.isSuccessful()) {
                resData = response.body().string();
            }
        } catch (IOException exc) {
            LogUtil.log4j2().warn(exc.getMessage());
        }

        return JSON.parseObject(resData, InputRobot.class).getText();
    }
}
